﻿#include <cstdlib>
#include <cstring>

#include "frame/test_macros.h"

#include "algorithm/xxtea.h"


/*
 * XTEA tests vectors (non-official)
 */

static const unsigned char xtea_test_key[6][16] = {
    {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f},
    {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f},
    {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f},
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};

static const unsigned char xtea_test_pt[6][8] = {
    {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48}, {0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41},
    {0x5a, 0x5b, 0x6e, 0x27, 0x89, 0x48, 0xd7, 0x7f}, {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48},
    {0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41}, {0x70, 0xe1, 0x22, 0x5d, 0x6e, 0x4e, 0x76, 0x55}};

static const unsigned char xtea_test_ct[6][8] = {
    {0x70, 0x6c, 0xd7, 0x32, 0x3e, 0xd8, 0x60, 0xe8}, {0x0d, 0x5a, 0x2d, 0x8b, 0x6a, 0x43, 0x18, 0x30},
    {0x0d, 0xa4, 0xba, 0xd3, 0xb4, 0x2a, 0x78, 0x85}, {0x62, 0xeb, 0x33, 0x08, 0x10, 0x86, 0x0a, 0x17},
    {0xd1, 0xbe, 0xdf, 0x50, 0xdc, 0xf2, 0x90, 0x43}, {0x47, 0xcc, 0x5f, 0xb9, 0x91, 0x90, 0x66, 0x6b}};

CASE_TEST(xxtea, basic) {
    util::xxtea_key key;
    unsigned char test_data[8];

    for (int i = 0; i < 6; ++i) {
        util::xxtea_setup(&key, xtea_test_key[i]);

        memcpy(test_data, xtea_test_pt[i], 8);
        util::xxtea_encrypt(&key, test_data, 8);
        CASE_EXPECT_EQ(0, memcmp(test_data, xtea_test_ct[i], 8));

        memcpy(test_data, xtea_test_ct[i], 8);
        util::xxtea_decrypt(&key, test_data, 8);
        CASE_EXPECT_EQ(0, memcmp(test_data, xtea_test_pt[i], 8));
    }
}

CASE_TEST(xxtea, input_output) {
    util::xxtea_key key;
    unsigned char test_data_in[8];
    unsigned char test_data_out[8];
    size_t olen = 0;

    for (int i = 0; i < 6; ++i) {
        util::xxtea_setup(&key, xtea_test_key[i]);

        memcpy(test_data_in, xtea_test_pt[i], 8);
        olen = 8;
        util::xxtea_encrypt(&key, test_data_in, 8, test_data_out, &olen);
        CASE_EXPECT_EQ(0, memcmp(test_data_out, xtea_test_ct[i], 8));
        CASE_EXPECT_EQ(8, olen);

        memcpy(test_data_in, xtea_test_ct[i], 8);
        olen = 8;
        util::xxtea_decrypt(&key, test_data_in, 8, test_data_out, &olen);
        CASE_EXPECT_EQ(0, memcmp(test_data_out, xtea_test_pt[i], 8));
        CASE_EXPECT_EQ(8, olen);
    }
}